﻿using AutoMapper;
using B.S.BasicData.API.Read.Application.Command.Menu;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Read.Application.Handler.Menu
{
    /// <summary>
    /// 获取菜单信息请求命令处理类(级联)
    /// </summary>
    public class GetMenuSelectHandler:IRequestHandler<GetMenuSelectCommand,ApiResult<List<MenuDTO>>>
    {
        IBaseRepository<MenuModel> menuRep;
        IMapper mapper;

        public GetMenuSelectHandler(IBaseRepository<MenuModel> menuRep, IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<MenuDTO>>> Handle(GetMenuSelectCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<MenuDTO>> res = new ApiResult<List<MenuDTO>>();
                res.Msg = "获取菜单信息";
                res.Code = ApiEnum.Success;
                res.Data = getmenu(0);
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }

        private List<MenuDTO> getmenu(int pid)
        {
            var menus=menuRep.GetAll().Where(x=>x.IsDeleted==false&&x.P_ID ==pid).ToList();

            var menudto=mapper.Map<List<MenuDTO>>(menus);
            foreach (var item in menudto)
            {
                item.Children = getmenu(item.Id);
            }
            return menudto;
        }
    }
}
